
import { Inject, Injectable } from '@angular/core';

import { DA_SERVICE_TOKEN, ITokenService } from '@delon/auth';
import { Subject } from 'rxjs';
import { RsocketService } from '@core';
import { CacheService } from '@delon/cache';

@Injectable()
export class MessageService {

  chats: any = {}

  private receiveSubject = new Subject<any>();
  receive$ = this.receiveSubject.asObservable();

  constructor(
    @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
    private rsocketService: RsocketService,
    private cacheService : CacheService 
  ) { 
    this.chats = this.cacheService.get("chats");
    this.rsocketService.responder$.subscribe(res=>{
      this.receive(res.data);
    });
  }



  send(sender, receiver, content) {
    const message = {
      fromId: sender,
      toId: receiver,
      content: content,
      type: "0"
    }

    if(this.chats[receiver]){
      this.chats[receiver].push(message);
    }else{
      this.chats[receiver] = [message]
    }
    return this.rsocketService.socket.requestResponse({
      data: message,
      metadata: String.fromCharCode('send'.length) + 'send'
    })
  }

  getMessages(receiver){
    if(this.chats[receiver]){
      return this.chats[receiver];
    }else{
      return [];
    }
      
  }

  receive(message:any){
    if(this.chats[message.receiver]){
      this.chats[message.receiver].push(message.data);
    }else{
      this.chats[message.receiver] = [message.data]
    }
    this.receiveSubject.next(message);
  }

}